#!/usr/bin/env bash
. ./scripts/devcontainer/_assert-in-container "$0" "$@"

set -euo pipefail

# Deploy Dark to production

# MANIFEST=""

# HELP="$(cat <<EOF
# Usage: $0 [OPTIONS]

# Deployment script for CI

# Options:
#   --manifest=...    Manifest containing container shas
#   --help            Display this menu.
# EOF
# )"

# for i in "$@"
# do
#   case "${i}" in
#     --manifest=*)
#       MANIFEST="${i/--manifest=/''}"
#       ;;
#     --help)
#       echo "$HELP"
#       exit 0
#       ;;
#     *)
#       echo "Unexpected argument: $i"
#       echo "$HELP"
#       exit 1
#       ;;
#   esac
# done

# set -x

#############################
# Ensure we got a good one
#############################
# LIGHTTODO
# ./scripts/deployment/shipit validate

#############################
# Lock before doing a deploy (unlocks on fail or at end of file)
#############################

cleanup_deploy_lock() {
  trap '' EXIT # some shells will call EXIT after the INT handler
  echo "Removing deploy lock"
  ./scripts/deployment/deploy-lock-one-remove
  exit 1
}

# Make sure we remove the lockfile if this script exits early for some reason
trap cleanup_deploy_lock INT QUIT TERM ERR

# We source this instead of running it in a subshell so that the trap works as expected
./scripts/deployment/deploy-lock-wait-and-acquire

#############################
# Check it's safe to deploy
#############################

# LIGHTTODO
# Check that the everything can be deployed
CHANGE_CAUSE="circle=${CIRCLE_BUILD_URL} ; orig-time: $(date); git-commit: $(git rev-parse --short HEAD)"

#############################
# Actually do the deploy
#############################
# LIGHTTODO

#########################
# Tell everyone about the deploy
#########################

./scripts/deployment/_notify-deployment-rollbar "${CHANGE_CAUSE}"
./scripts/deployment/_notify-deployment-honeycomb "${CHANGE_CAUSE}"

####################
# Unlock post-deploy
####################
./scripts/deployment/deploy-lock-one-remove
